package com.app.myApp.control;

import com.app.myApp.dataobject.*;
import com.app.myApp.model.Response;
import com.app.myApp.service.KnowledgeService;
import com.app.myApp.utils.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api/knowledge")
public class KnowledgeController {

    @Autowired
    private KnowledgeService knowledgeService;

    /**
     * 获取系统知识库列表
     */
    @GetMapping("/system")
    public ResponseEntity<Response> getSystemKnowledgeBases() {
        try {
            List<SystemKnowledgeBasesDO> systemKbs = knowledgeService.getSystemKnowledgeBases();
            return new ResponseEntity<>(Response.success(systemKbs), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("获取系统知识库失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 获取用户个人知识库列表
     */
    @GetMapping("/user")
    public ResponseEntity<Response> getUserKnowledgeBases(@RequestParam String email) {
        // 校验参数
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            List<KnowledgeBasesDO> userKbs = knowledgeService.getUserKnowledgeBases(email);
            return new ResponseEntity<>(Response.success(userKbs), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("获取个人知识库失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 创建新的知识库（含文件上传）
     */
    @PostMapping("/create")
    public ResponseEntity<Response> createKnowledgeBase(
            @RequestParam String name,
            @RequestParam String description,
            @RequestParam String email,
            @RequestParam("files") MultipartFile[] files) {

        // 校验参数
        if (!StringUtils.hasText(name)) {
            return new ResponseEntity<>(Response.error("知识库名称不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (files == null || files.length == 0) {
            return new ResponseEntity<>(Response.error("请至少上传一个文件"), HttpStatus.BAD_REQUEST);
        }

        try {
            KnowledgeBasesDO newKb = knowledgeService.createKnowledgeBase(name, description, email, files);
            return new ResponseEntity<>(Response.success(newKb), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("创建知识库失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 上传文件到已有知识库
     */
    @PostMapping("/upload-file")
    public ResponseEntity<Response> uploadFileToKnowledgeBase(
            @RequestParam String kbId,
            @RequestParam String email,
            @RequestParam("file") MultipartFile file) {

        // 校验参数
        if (!StringUtils.hasText(kbId)) {
            return new ResponseEntity<>(Response.error("知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (file == null || file.isEmpty()) {
            return new ResponseEntity<>(Response.error("请选择要上传的文件"), HttpStatus.BAD_REQUEST);
        }

        try {
            KnowledgeFilesDO uploadedFile = knowledgeService.uploadFileToKnowledgeBase(kbId, email, file);
            return new ResponseEntity<>(Response.success(uploadedFile), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("文件上传失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 获取知识库中的文件列表
     */
    @GetMapping("/files")
    public ResponseEntity<Response> getFilesByKnowledgeId(@RequestParam String kbId) {
        // 校验参数
        if (!StringUtils.hasText(kbId)) {
            return new ResponseEntity<>(Response.error("知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            List<KnowledgeFilesDO> files = knowledgeService.getFilesByKnowledgeId(kbId);
            return new ResponseEntity<>(Response.success(files), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("获取文件列表失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 删除知识库中的文件
     */
    @DeleteMapping("/delete-file")
    public ResponseEntity<Response> deleteFile(@RequestBody Map<String, String> params) {
        // 校验参数
        String kbId = params.get("kbId");
        String fileId = params.get("fileId");
        String email = params.get("email");

        if (!StringUtils.hasText(kbId)) {
            return new ResponseEntity<>(Response.error("知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(fileId)) {
            return new ResponseEntity<>(Response.error("文件ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            boolean success = knowledgeService.deleteFile(kbId, fileId, email);
            if (success) {
                return new ResponseEntity<>(Response.success(null), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Response.error("文件删除失败"), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("删除文件失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 删除知识库
     */
    @DeleteMapping("/delete")
    public ResponseEntity<Response> deleteKnowledgeBase(@RequestBody Map<String, String> params) {
        // 校验参数
        String kbId = params.get("kbId");
        String email = params.get("email");

        if (!StringUtils.hasText(kbId)) {
            return new ResponseEntity<>(Response.error("知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            boolean success = knowledgeService.deleteKnowledgeBase(kbId, email);
            if (success) {
                return new ResponseEntity<>(Response.success(null), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Response.error("知识库删除失败"), HttpStatus.OK);
            }
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("删除知识库失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 选择知识库关联到机器人
     */
    @PostMapping("/select")
    public ResponseEntity<Response> selectKnowledgeBase(@RequestBody Map<String, Object> params) {
        // 校验参数
        if (!params.containsKey("robotId") || params.get("robotId") == null) {
            return new ResponseEntity<>(Response.error("机器人ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!params.containsKey("knowledgeBaseId") || !StringUtils.hasText(params.get("knowledgeBaseId").toString())) {
            return new ResponseEntity<>(Response.error("知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            Long robotId = Long.parseLong(params.get("robotId").toString());
            String knowledgeBaseId = params.get("knowledgeBaseId").toString();
            boolean isSystem = params.containsKey("isSystem") ? (boolean) params.get("isSystem") : false;

            boolean success = knowledgeService.selectKnowledgeBase(robotId, knowledgeBaseId, isSystem);
            if (success) {
                return new ResponseEntity<>(Response.success(null), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Response.error("选择知识库失败"), HttpStatus.OK);
            }
        } catch (NumberFormatException e) {
            return new ResponseEntity<>(Response.error("机器人ID格式不正确"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("选择知识库失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 取消选择知识库
     */
    @PostMapping("/deselect")
    public ResponseEntity<Response> deselectKnowledgeBase(@RequestBody Map<String, Object> params) {
        // 校验参数
        if (!params.containsKey("robotId") || params.get("robotId") == null) {
            return new ResponseEntity<>(Response.error("机器人ID不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            Long robotId = Long.parseLong(params.get("robotId").toString());

            boolean success = knowledgeService.deselectKnowledgeBase(robotId);
            if (success) {
                return new ResponseEntity<>(Response.success(null), HttpStatus.OK);
            } else {
                return new ResponseEntity<>(Response.error("取消选择失败"), HttpStatus.OK);
            }
        } catch (NumberFormatException e) {
            return new ResponseEntity<>(Response.error("机器人ID格式不正确"), HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("取消选择失败: " ), HttpStatus.OK);
        }
    }

    /**
     * 获取机器人当前选择的知识库
     */
    @GetMapping("/selected")
    public ResponseEntity<Response> getSelectedKnowledgeBase(@RequestParam Long robotId) {
        // 校验参数
        if (robotId == null) {
            return new ResponseEntity<>(Response.error("机器人ID不能为空"), HttpStatus.BAD_REQUEST);
        }

        try {
            RobotAndKnowledgeBasesDO selectedKb = knowledgeService.getSelectedKnowledgeBase(robotId);
            return new ResponseEntity<>(Response.success(selectedKb), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("获取已选择知识库失败: " ), HttpStatus.OK);
        }
    }


    // ------------------- 新增：管理员-创建系统知识库接口 -------------------
    @PostMapping("/system/create")
    public ResponseEntity<Response> createSystemKnowledgeBase(
            @RequestParam String name,
            @RequestParam String description,
            @RequestParam String email,
            @RequestParam("files") MultipartFile[] files) {
        // 1. 参数校验
        if (!StringUtils.hasText(name)) {
            return new ResponseEntity<>(Response.error("系统知识库名称不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (files == null || files.length == 0) {
            return new ResponseEntity<>(Response.error("请至少上传一个文件"), HttpStatus.BAD_REQUEST);
        }
        // 2. 权限快速校验（避免进入Service后抛异常）
        if (!AuthUtil.isAdmin(email)) {
            return new ResponseEntity<>(Response.error("非管理员无权限操作"), HttpStatus.FORBIDDEN);
        }

        try {
            SystemKnowledgeBasesDO newSystemKb = knowledgeService.createSystemKnowledgeBase(name, description, email, files);
            return new ResponseEntity<>(Response.success(newSystemKb), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("创建系统知识库失败: " + e.getMessage()), HttpStatus.OK);
        }
    }

    // ------------------- 新增：管理员-上传文件到系统知识库接口 -------------------
    @PostMapping("/system/upload-file")
    public ResponseEntity<Response> uploadFileToSystemKb(
            @RequestParam String systemKbId,
            @RequestParam String email,
            @RequestParam("file") MultipartFile file) {
        // 1. 参数校验
        if (!StringUtils.hasText(systemKbId)) {
            return new ResponseEntity<>(Response.error("系统知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (file == null || file.isEmpty()) {
            return new ResponseEntity<>(Response.error("请选择要上传的文件"), HttpStatus.BAD_REQUEST);
        }
        // 2. 权限校验
        if (!AuthUtil.isAdmin(email)) {
            return new ResponseEntity<>(Response.error("非管理员无权限操作"), HttpStatus.FORBIDDEN);
        }

        try {
            SystemKnowledgeFilesDO uploadedFile = knowledgeService.uploadFileToSystemKb(systemKbId, email, file);
            return new ResponseEntity<>(Response.success(uploadedFile), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("文件上传失败: " + e.getMessage()), HttpStatus.OK);
        }
    }

    // ------------------- 新增：管理员-删除系统知识库接口 -------------------
    @DeleteMapping("/system/delete")
    public ResponseEntity<Response> deleteSystemKnowledgeBase(@RequestBody Map<String, String> params) {
        // 1. 参数校验
        String systemKbId = params.get("systemKbId");
        String email = params.get("email");
        if (!StringUtils.hasText(systemKbId)) {
            return new ResponseEntity<>(Response.error("系统知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        // 2. 权限校验
        if (!AuthUtil.isAdmin(email)) {
            return new ResponseEntity<>(Response.error("非管理员无权限操作"), HttpStatus.FORBIDDEN);
        }

        try {
            boolean success = knowledgeService.deleteSystemKnowledgeBase(systemKbId, email);
            return success ? new ResponseEntity<>(Response.success(null), HttpStatus.OK)
                    : new ResponseEntity<>(Response.error("删除系统知识库失败"), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("删除失败: " + e.getMessage()), HttpStatus.OK);
        }
    }

    // ------------------- 新增：管理员-删除系统知识库文件接口 -------------------
    @DeleteMapping("/system/delete-file")
    public ResponseEntity<Response> deleteSystemKbFile(@RequestBody Map<String, String> params) {
        // 1. 参数校验
        String systemKbId = params.get("systemKbId");
        String fileId = params.get("fileId");
        String email = params.get("email");
        if (!StringUtils.hasText(systemKbId)) {
            return new ResponseEntity<>(Response.error("系统知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(fileId)) {
            return new ResponseEntity<>(Response.error("文件ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        // 2. 权限校验
        if (!AuthUtil.isAdmin(email)) {
            return new ResponseEntity<>(Response.error("非管理员无权限操作"), HttpStatus.FORBIDDEN);
        }

        try {
            boolean success = knowledgeService.deleteSystemKbFile(systemKbId, fileId, email);
            return success ? new ResponseEntity<>(Response.success(null), HttpStatus.OK)
                    : new ResponseEntity<>(Response.error("删除系统知识库文件失败"), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("删除失败: " + e.getMessage()), HttpStatus.OK);
        }
    }

    /**
     * 新增：管理员-获取系统知识库文件列表接口
     */
    @GetMapping("/system/files")
    public ResponseEntity<Response> getFilesBySystemKbId(
            @RequestParam String systemKbId,
            @RequestParam String email) {  // 必须传递管理员邮箱用于权限校验
        // 1. 参数校验
        if (!StringUtils.hasText(systemKbId)) {
            return new ResponseEntity<>(Response.error("系统知识库ID不能为空"), HttpStatus.BAD_REQUEST);
        }
        if (!StringUtils.hasText(email)) {
            return new ResponseEntity<>(Response.error("邮箱不能为空"), HttpStatus.BAD_REQUEST);
        }
        // 2. 管理员权限校验（核心！）
        if (!AuthUtil.isAdmin(email)) {
            return new ResponseEntity<>(Response.error("非管理员无权限查看系统知识库文件"), HttpStatus.FORBIDDEN);
        }

        try {
            List<SystemKnowledgeFilesDO> files = knowledgeService.getFilesBySystemKbId(systemKbId);
            return new ResponseEntity<>(Response.success(files), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(Response.error("获取系统知识库文件列表失败: " + e.getMessage()), HttpStatus.OK);
        }
    }
}
